package com.luo.backend.service;

import com.luo.backend.dto.AddressRequest;
import com.luo.backend.dto.AddressResponse;
import com.luo.backend.entity.UserAddress;
import com.luo.backend.repository.UserAddressRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 地址服务类
 */
@Service
public class AddressService {
    
    private static final Logger logger = LoggerFactory.getLogger(AddressService.class);
    
    @Autowired
    private UserAddressRepository addressRepository;
    
    /**
     * 获取用户地址列表
     */
    public List<AddressResponse> getUserAddresses(Long userId) {
        logger.info("获取用户{}的地址列表", userId);
        
        List<UserAddress> addresses = addressRepository.findByUserIdOrderByIsDefaultDescCreatedAtDesc(userId);
        return addresses.stream()
                .map(AddressResponse::new)
                .collect(Collectors.toList());
    }
    
    /**
     * 添加收货地址
     */
    @Transactional
    public AddressResponse addAddress(Long userId, AddressRequest request) {
        logger.info("用户{}添加新地址", userId);
        
        // 如果设置为默认地址，先取消其他默认地址
        if (request.getIsDefault()) {
            addressRepository.clearUserDefaultAddresses(userId);
        }
        
        // 创建新地址
        UserAddress address = new UserAddress();
        address.setUserId(userId);
        address.setName(request.getName());
        address.setPhone(request.getPhone());
        address.setProvince(request.getProvince());
        address.setCity(request.getCity());
        address.setDistrict(request.getDistrict());
        address.setAddress(request.getAddress());
        address.setIsDefault(request.getIsDefault());
        
        address = addressRepository.save(address);
        logger.info("用户{}成功添加地址，ID: {}", userId, address.getId());
        
        return new AddressResponse(address);
    }
    
    /**
     * 更新收货地址
     */
    @Transactional
    public AddressResponse updateAddress(Long userId, Long addressId, AddressRequest request) {
        logger.info("用户{}更新地址{}", userId, addressId);
        
        Optional<UserAddress> addressOpt = addressRepository.findByIdAndUserId(addressId, userId);
        if (!addressOpt.isPresent()) {
            throw new RuntimeException("地址不存在");
        }
        
        UserAddress address = addressOpt.get();
        
        // 如果设置为默认地址，先取消其他默认地址
        if (request.getIsDefault() && !address.getIsDefault()) {
            addressRepository.clearUserDefaultAddresses(userId);
        }
        
        // 更新地址信息
        address.setName(request.getName());
        address.setPhone(request.getPhone());
        address.setProvince(request.getProvince());
        address.setCity(request.getCity());
        address.setDistrict(request.getDistrict());
        address.setAddress(request.getAddress());
        address.setIsDefault(request.getIsDefault());
        
        address = addressRepository.save(address);
        logger.info("用户{}成功更新地址{}", userId, addressId);
        
        return new AddressResponse(address);
    }
    
    /**
     * 删除收货地址
     */
    @Transactional
    public void deleteAddress(Long userId, Long addressId) {
        logger.info("用户{}删除地址{}", userId, addressId);
        
        Optional<UserAddress> addressOpt = addressRepository.findByIdAndUserId(addressId, userId);
        if (!addressOpt.isPresent()) {
            throw new RuntimeException("地址不存在");
        }
        
        addressRepository.deleteById(addressId);
        logger.info("用户{}成功删除地址{}", userId, addressId);
    }
    
    /**
     * 设置默认地址
     */
    @Transactional
    public AddressResponse setDefaultAddress(Long userId, Long addressId) {
        logger.info("用户{}设置默认地址{}", userId, addressId);
        
        Optional<UserAddress> addressOpt = addressRepository.findByIdAndUserId(addressId, userId);
        if (!addressOpt.isPresent()) {
            throw new RuntimeException("地址不存在");
        }
        
        // 先取消所有默认地址
        addressRepository.clearUserDefaultAddresses(userId);
        
        // 设置新的默认地址
        UserAddress address = addressOpt.get();
        address.setIsDefault(true);
        address = addressRepository.save(address);
        
        logger.info("用户{}成功设置默认地址{}", userId, addressId);
        return new AddressResponse(address);
    }
    
    /**
     * 获取默认地址
     */
    public AddressResponse getDefaultAddress(Long userId) {
        logger.info("获取用户{}的默认地址", userId);
        
        Optional<UserAddress> addressOpt = addressRepository.findByUserIdAndIsDefaultTrue(userId);
        if (!addressOpt.isPresent()) {
            throw new RuntimeException("未设置默认地址");
        }
        
        return new AddressResponse(addressOpt.get());
    }
}

